<template>
    <el-form label-width="80px">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>

        <el-form-item label="品牌">
            <el-select placeholder="请选择" v-model="spuInfo.tmId">
                <el-option v-for="item in tmList" :key="item.id" :label="item.tmName" :value="item.id" />
            </el-select>
        </el-form-item>

        <el-form-item label="SPU描述">
            <el-input type="textarea" rows="6" placeholder="SPU描述" v-model="spuInfo.description"></el-input>
        </el-form-item>

        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList as UploadUserFile[]" :action="`${baseUrl}/admin/product/upload`"
                list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>

        <el-form-item label="销售属性">
            <el-select :placeholder="`还有${unUsedSaleAttrList.length}个未选`" v-model="tempSaleAtte">
                <el-option v-for="item in unUsedSaleAttrList" :key="item.id" :label="item.name"
                    :value="`${item.id}:${item.name}`">
                </el-option>
            </el-select>
            <el-button type="primary" :disabled="!tempSaleAtte" @click="addSaleAtttr">添加销售属性</el-button>
        </el-form-item>

        <el-form-item>
            <el-table :data="spuSaleAttrList" border stripe>
                <el-table-column type="index" width="80" align="center" label="序号" />
                <el-table-column label="属性名" prop="saleAttrName" />
                <el-table-column label="属性值名称列表">
                    <template v-slot="{ row, $index }">
                        <el-tag v-for="tag in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable
                            :disable-transitions="false" @close="row.spuSaleAttrValueList.splice($index, 1)">
                            {{ tag.saleAttrValueName }}
                        </el-tag>
                        <el-input v-model="row.inputValue" v-if="row.isEdit" ref="editEle" class="ml-1 w-20"
                            size="small" @blur="changeToLook(row)" />
                        <el-button v-else @click="changeToEdit(row)" class="button-new-tag ml-1" size="small">
                            添加属性值
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ $index }">
                        <el-button type="danger" icon="ele-Delete" @click="spuSaleAttrList.splice($index, 1)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>

        <el-form-item label="">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { requestBaseSaleAttrList, requestSaveSpuInfo, requestSpuImgList, requestSpuSaleAttrList, requestUpdateSpuInfo, type BaseSaleAttrListType, type SpuImageListType, type SpuInfoType, type SpuSaleAttrItemType, type SpuSaleAttrListType } from '@/api/spu';
import { requestAllTmList, type TmListType } from '@/api/tradmark';

export default defineComponent({
    name: "SupFrom",
});
</script>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
const baseUrl = import.meta.env.VITE_API_URL;

//1.接收父组件传递的自定义事件，点击取消调用，回到spuList组件
const emit = defineEmits<{
    (event: 'setState', state: number, row?: SpuInfoType): void
}>()

//2.接收父组件传递的props
const props = defineProps<{
    spuInfo: SpuInfoType
}>()

//判断是新增还是修改进入的当前组件，去请求当前From需要的数据(其中新增需要发送:1.品牌列表2.所有销售属性列表,修改需要发送:1.品牌列表2.所有销售属性列表3.当前spu图片列表4.当前spu的属性列表)
//声明一些数据 保存品牌列表、所有销售属性列表、当前spu图片列表、当前spu属性列表
const tmList = ref<TmListType[]>([])
const saleAttrList = ref<BaseSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])
//封装函数初始化请求所有当前组件需要的数据
const getAllUseData = async () => {
    if (!props.spuInfo.id) {
        try {
            //新增逻辑发送两个请求
            const result1 = await requestAllTmList()
            tmList.value = result1
            const result2 = await requestBaseSaleAttrList()
            saleAttrList.value = result2
        } catch (error) {
            //失败提示
            ElMessage.error("新增初始请求数据失败")
        }
    } else {
        //修改逻辑发送4个请求
        const promise1 = requestAllTmList()
        const promise2 = requestBaseSaleAttrList()
        const promise3 = requestSpuImgList(props.spuInfo.id as number)
        const promise4 = requestSpuSaleAttrList(props.spuInfo.id as number)
        try {
            const result = await Promise.all([promise1, promise2, promise3, promise4])
            tmList.value = result[0];
            saleAttrList.value = result[1];
            spuImageList.value = result[2];
            //4.处理照片墙数据,要在spu图片列表数据请求回来之后才能操作
            spuImageList.value.forEach((item) => {
                item.name = item.imgName
                item.url = item.imgUrl
            })
            spuSaleAttrList.value = result[3];
            spuSaleAttrList.value.forEach((item) => {
                //给spu的销售属性列表的每一项添加一个isEdit属性,代表当前内部的属性值是添加模式还是编辑模式
                item.isEdit = false
                //给spu销售属性列表添加inputValue属性保存当前的销售属性输入框的值
                item.inputValue = ""
            })
        } catch (error) {
            ElMessage.error("修改初始请求数据失败!")
        }
    }
}
//3.初始化请求需要的数据
onMounted(() => {
    getAllUseData()
});


//5.计算属性计算没有使用过的销售属性列表
const unUsedSaleAttrList = computed(() => {
    //.处理所有销售属性数据
    return saleAttrList.value = saleAttrList.value.filter((item) => {
        return !spuSaleAttrList.value.some((item2) => {
            //判断spu中的销售属性如果有，所有销售属性中就不能有
            return item2.saleAttrName === item.name
        })
    })
})

//定义数据收集用户临时选择的销售属性
const tempSaleAtte = ref("")
//6.点击添加销售属性的回调
const addSaleAtttr = () => {
    //拿到保存的临时销售属性数据
    const [baseSaleAttrId, saleAttrName] = tempSaleAtte.value.split(":")
    //创建一条要添加的销售属性数据
    const newsaleAttr = {
        baseSaleAttrId: +baseSaleAttrId,
        saleAttrName: saleAttrName,
        spuSaleAttrValueList: []
    }
    //把这条销售属性添加到spu销售属性列表中
    spuSaleAttrList.value.push(newsaleAttr)
    //添加之后清空临时销售属性
    tempSaleAtte.value = ""
}

//保存当前的处在编辑模式的表单元素
const editEle = ref<HTMLInputElement>();
//7.点击button切换编辑模式的事件函数
const changeToEdit = (row: SpuSaleAttrItemType) => {
    //切换模式
    row.isEdit = true;
    //自动获取焦点
    nextTick(() => {
        editEle.value?.focus();
    });
};

//8.失去焦点的逻辑
const changeToLook = (row: SpuSaleAttrItemType) => {
    //拿到输入框的值
    const oldInputValue = row.inputValue

    //判断输入框的值是否为空
    if (!oldInputValue?.trim()) {
        //输入框为空，用户什么也没输入，恢复button即可
        row.isEdit = false
        return;
    }

    //判断输入框内容和已有的重复
    const isRepect = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName === oldInputValue
    })

    if (isRepect) {
        //输入重复内容，删除，在恢复为button
        row.isEdit = false
        //清空输入框的值
        row.inputValue = ""
        ElMessage.error("输入的内容重复!")
        return;
    }

    //输入内容正常创建一个要添加的销售属性值对象
    const newSaleAttrValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: oldInputValue
    }
    //插入到销售属性值列表
    row.spuSaleAttrValueList.push(newSaleAttrValue)

    //最后都要切换模式清空输入框的值
    row.isEdit = false
    row.inputValue = ""
}


//9.点击保存的回调
const save = async () => {
    //收集spu图片列表数据
    const newSpuImageList = spuImageList.value.map((item) => {
        //判断有没有response
        if (item.response) {
            return {
                imgUrl: item.response.data as string,
                imgName: item.name as string
            }
        } else {
            return {
                imgUrl: item.url as string,
                imgName: item.name as string
            }
        }
    })

    //整理SaleAttrvalueList数据，因为里边多了isEdit 和 inputValue两个属性
    spuSaleAttrList.value.forEach((item) => {
        delete item.isEdit
        delete item.inputValue
    })

    //把整理的数据赋值到spuInfo
    props.spuInfo.spuImageList = newSpuImageList
    props.spuInfo.spuSaleAttrList = spuSaleAttrList.value

    //提交数据发送请求
    try {
        if (props.spuInfo.id) {
            //修改
            await requestUpdateSpuInfo(props.spuInfo)
        } else {
            //新增操作
            await requestSaveSpuInfo(props.spuInfo);
        }

        //不管是新增还是修改都回到首页
        emit("setState", 0);
    } catch (error) {
        ElMessage.error(props.spuInfo.id ? '修改spu失败' : '添加spu失败!')
    }


}


//照片墙逻辑
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
</script>